package com.alipay.app.groupmeal.standard.util;

import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.widget.Toast;

import com.alipay.app.groupmeal.standard.bean.SerialPortReceive;
import com.alipay.app.groupmeal.standard.bean.SerialPortSend;
import com.alipay.app.groupmeal.standard.ui.MainActivity;
import com.alipay.app.groupmeal.standard.ui.c.abcp.CPayingAbcpActivity2;

import top.keepempty.sph.library.SerialPortConfig;
import top.keepempty.sph.library.SerialPortHelper;
import top.keepempty.sph.library.SphCmdEntity;
import top.keepempty.sph.library.SphResultCallback;

public class SerialPortHelperUtil {

    private static SerialPortHelperUtil serialPortHelperUtil;

    private static SerialPortHelper serialPortHelper;

    private static final StringBuilder receiveText = new StringBuilder();

    public static synchronized SerialPortHelperUtil getInstance() {
        if(serialPortHelperUtil == null) {
            serialPortHelperUtil = new SerialPortHelperUtil();
        }
        return serialPortHelperUtil;
    }

    public synchronized SerialPortHelper newSerialPortHelper(Context context) {
        if (serialPortHelper == null) {
            serialPortHelper = new SerialPortHelper(12800);
            serialPortHelper.setConfigInfo(initConfig());
            if(!serialPortHelper.isOpenDevice()) {
                boolean isOpen = serialPortHelper.openDevice();
                if(!isOpen){
                    Toast.makeText(context, "串口打开失败！", Toast.LENGTH_LONG).show();
                }
                // 数据接收回调
                serialPortHelper.setSphResultCallback(getResultCallback(context));
            }
        }
        return serialPortHelper;
    }

    private static SerialPortConfig initConfig() {
        SerialPortConfig serialPortConfig = new SerialPortConfig();
        serialPortConfig.mode = 0;  // 是否使用原始模式(Raw Mode)方式来通讯
        serialPortConfig.path = "/dev/ttyS2";  // 串口地址
        serialPortConfig.baudRate = 9600; // 波特率
        serialPortConfig.dataBits = 8; // 数据位 取值 位 7或 8
        serialPortConfig.parity = 'N';// 检验类型 取值 N ,E, O
        serialPortConfig.stopBits = 1; // 停止位 取值 1 或者 2
        return serialPortConfig;
    }

    private static SphResultCallback getResultCallback(Context context) {
        return new SphResultCallback() {
            @Override
            public void onSendData(SphCmdEntity sendCom) {
                Log.d("MainActivity", "发送命令：" + sendCom.commandsHex);
            }

            @Override
            public void onReceiveData(SphCmdEntity data) {
                Log.d("MainActivity", "收到命令：" + data.commandsHex);
                receiveText.append(data.commandsHex);
                if(receiveText.toString().endsWith("DB")) {
                    if (!ActivityUtil.isActivityRunning(context, "com.alipay.app.groupmeal.standard.ui.c.abcp.CPayingAbcpActivity2")) {
                        try {
                            //检测包序号
                            String serialNumber = receiveText.substring(10, 12);
                            if(serialNumber.equals(SerialPortSend.getInstance().getPacketSerialNumber())) {
                                String command = SerialPortSend.getInstance().getSendCommand();
                                SerialPortHelper serialPortHelper = SerialPortHelperUtil.getInstance().newSerialPortHelper(context);
                                serialPortHelper.addCommands(command.getBytes());
                                throw new RuntimeException("包序号相同直接返回上次包结果");
                            }
                            //解析数据
                            SerialPortReceive.getInstance().receiveData(receiveText.toString());
                            //校验数据
                            String verifyCode = receiveText.substring(receiveText.length() - 4, receiveText.length() - 2);
                            if(!SerialPortReceive.getInstance().verify(verifyCode)) {
                                throw new RuntimeException("校验不通过!");
                            }
                            String costAmount = SerialPortReceive.getInstance().getCostAmount();
                            // activity未在运行，可以选择停止服务或处理其他逻辑
                            Intent intent = new Intent(MainActivity.mActivity, CPayingAbcpActivity2.class);
                            intent.putExtra("amount", costAmount);
                            MainActivity.mActivity.startActivity(intent);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                    receiveText.delete(0, receiveText.length());
                }
            }

            @Override
            public void onComplete() {
                Log.d("MainActivity", "完成");
            }
        };
    }
}
